package com.sram.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * 类名：MD5Utils
 * 功能：使用md5的算法进行加密
 * 详细：传递一个String 返回一个MD5加密信息
 * 版本：1.0
 * 日期：2013-11-21
 * 说明：.....
 * @author JavaPlus
 *
 */
public class MD5Utils {
	/**
	 * 使用md5的算法进行加密
	 */
//	public static String MD5(String plainText) {
//		byte[] secretBytes = null;
//		try {
//			secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
//			
//		} catch (NoSuchAlgorithmException e) {
//			throw new RuntimeException("没有md5这个算法！");
//		}
//		String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
//		// 如果生成数字未满32位，需要前面补0
//		for (int i = 0; i < 32 - md5code.length(); i++) {
//			md5code = "0" + md5code;
//		}
//		return md5code;
//	}

	/**
	 * 截取20位UUID字符串
	 * 功能：订单号、主键
	 * @author JavaPlus
	 * @return String
	 */
	public static String MD5CUT20() {
		return java.util.UUID.randomUUID().toString().replace("-", "").substring(0,20);
	}
	
	public static String getUUID() {
		return java.util.UUID.randomUUID().toString().replace("-", "");
	}
	public static void main(String[] args) {
		for(int i = 0; i < 20;i++){
			System.out.println(MD5Utils.getUUID());
		}
		
	}

	
	private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
	
	private static String byteArrayToHexString(byte[] b) { 
		StringBuffer resultSb = new StringBuffer(); 
		for (int i = 0; i < b.length; i++) { 
			resultSb.append(byteToHexString(b[i])); 
		} 
		return resultSb.toString(); 
	} 

	private static String byteToHexString(byte b) { 
		int n = b; 
		if (n < 0) n = 256 + n; 
		int d1 = n / 16; 
		int d2 = n % 16; 
		return hexDigits[d1] + hexDigits[d2]; 
	} 
	/**
	 * MD5加密  32位
	 * @param origin
	 * @return
	 */
	public static String MD5(String origin) { 
		String resultString = null; 
		try { 
			resultString=new String(origin); 
			MessageDigest md = MessageDigest.getInstance("MD5"); 
			resultString=byteArrayToHexString(md.digest(resultString.getBytes())); 
		} 
		catch (Exception ex) {
			ex.printStackTrace();
		} 
		return resultString; 
	}
}
